package controlmercancias.util;

import java.net.*;
import java.io.*;

public class SocketManager {

    public static final String CRLF = "\r\n";
    private Socket mySocket;
    private DataOutputStream bufferEscritura;
    private BufferedReader bufferLectura;

    public SocketManager(Socket sock) throws IOException {
        this.mySocket = sock;
        initStreams();
    }

    public SocketManager(InetAddress address, int port) throws IOException {
        mySocket = new Socket(address, port);
        initStreams();
    }

    public SocketManager(String host, int port) throws IOException {
        mySocket = new Socket(host, port);
        initStreams();
    }

    private void initStreams() throws IOException {
        bufferEscritura = new DataOutputStream(mySocket.getOutputStream());
        bufferLectura = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
    }

    public void close() throws IOException {
        closeStreams();
        closeSocket();
    }

    private void closeStreams() throws IOException {
        bufferEscritura.close();
        bufferLectura.close();
    }

    private void closeSocket() throws IOException {
        mySocket.close();
    }

    public String readLine() throws IOException {
        return bufferLectura.readLine();
    }

    /**
     * Escribe el contenido y acaba con un salto de línea
     * @param contenido El contenido a escribir
     * @throws IOException 
     */
    public void write(String contenido) throws IOException {
        bufferEscritura.writeBytes(contenido + CRLF);
        flush();
    }
    
    /**
     * Fuerza la salida de los datos del buffer
     * @throws IOException 
     */
    public void flush() throws IOException {
        bufferEscritura.flush();
    }
}
